package com.mediacloud.app.newsmodule.view

import android.app.Activity
import android.graphics.Rect
import android.view.*
import android.widget.PopupWindow

class SoftKeyboardHeightProvider : PopupWindow, ViewTreeObserver.OnGlobalLayoutListener {

    var rootView: View? = null
    var mActivity: Activity? = null
    var heightMax: Int = 0
    var listener: KeyboardListener? = null
    var lastKeyboardHeight = -1
    var isFirstLayout = true

    constructor(context: Activity) : super(context) {
        mActivity = context
        rootView = View(context)
        contentView = rootView
        rootView?.viewTreeObserver?.addOnGlobalLayoutListener(this)

        //设置宽度为0，高度为全屏
        width = 0
        height = ViewGroup.LayoutParams.MATCH_PARENT

        //设置键盘弹出方式
        softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        inputMethodMode = PopupWindow.INPUT_METHOD_NEEDED
    }

    fun init() {
        if (!isShowing) {
            var decorView = mActivity?.window?.decorView ?: return
            decorView.post {
                showAtLocation(decorView, Gravity.NO_GRAVITY, 0, 0)
            }
        }
    }

    override fun onGlobalLayout() {
        var rect = Rect()
        rootView?.getWindowVisibleDisplayFrame(rect)
        if (rect.bottom > heightMax) {
            heightMax = rect.bottom
        }
        var keyboardHeight = heightMax - rect.bottom
        if (listener != null && keyboardHeight != lastKeyboardHeight && !isFirstLayout) {
            listener?.onHeightChanged(keyboardHeight)
        }
        lastKeyboardHeight = keyboardHeight
        isFirstLayout = false

    }

    interface KeyboardListener {
        fun onHeightChanged(heigt: Int)
    }
}